<script >
$(".tax_rate").blur(function(){
  $(this).css("background-color","#D6D6FF");
	var flag  = isInteger($(this).val());
	if(!flag)
	{
		alert("税率不是数字");return ;
	}
	if($(this).parent().prev().children().val()==1)
	{
		 var obj    = $(this).parent().parent();
		 var number = obj.children('td').eq(4).find('input').val();
		 var price  = obj.children('td').eq(3).find('input').val();
		 var str  = $("#p_id").children('td').eq(5).html();
		 var strs = obj.children('td').eq(5).html();
		 var total	= (Number(number)*Number(price)*(1+Number(obj.children('td').eq(7).find('input').val())/100)).toFixed(2);
		 var totals =(Number(str.replace(/,/g,""))-Number(strs.replace(/,/g,""))+Number(total)).toFixed(2);
		 obj.children('td').eq(5).html(total);
		 $("#p_id").children('td').eq(5).html(totals);	
	}else{
     var obj    = $(this).parent().parent();
		 var number = obj.children('td').eq(4).find('input').val();
		 var price  = obj.children('td').eq(3).find('input').val();
		 var str  = $("#p_id").children('td').eq(5).html();
		 var strs = obj.children('td').eq(5).html();
		 var total	= (Number(number)*Number(price)).toFixed(2);
		 var totals =(Number(str.replace(/,/g,""))-Number(strs.replace(/,/g,""))+Number(total)).toFixed(2);
		 obj.children('td').eq(5).html(total);
		 $("#p_id").children('td').eq(5).html(totals);			

	}
});
$(".field").change(function(){
  $(this).css("background-color","#FFFFCC");
	if($(this).val()==1)
	{
		 var obj    = $(this).parent().parent();
		 var number = obj.children('td').eq(4).find('input').val();
		 var price  = obj.children('td').eq(3).find('input').val();
		 var total	= (Number(number)*Number(price)*(1+Number(obj.children('td').eq(7).find('input').val())/100)).toFixed(2);
		 var str  = $("#p_id").children('td').eq(5).html();
		 var strs = obj.children('td').eq(5).html();
		 var totals =(Number(str.replace(/,/g,""))-Number(strs.replace(/,/g,""))+Number(total)).toFixed(2);
		 obj.children('td').eq(5).html(total);
		 $("#p_id").children('td').eq(5).html(totals);	
	}else{
		 var obj    = $(this).parent().parent();
		 var number = obj.children('td').eq(4).find('input').val();
		 var price  = obj.children('td').eq(3).find('input').val();
		 var total	= (Number(number)*Number(price)).toFixed(2);
		 var str  = $("#p_id").children('td').eq(5).html();
		 var strs = obj.children('td').eq(5).html();

		 var totals =(Number(str.replace(/,/g,""))-Number(strs.replace(/,/g,""))+Number(total)).toFixed(2);
		 obj.children('td').eq(5).html(total);
		 $("#p_id").children('td').eq(5).html(totals);	

	}
});

$(function(){
$.datepicker.setDefaults({ dateFormat: 'yy-mm-dd' });
						

							$(document).on('focus',".datepicker", function(e){
							   var strs= new Array();
								var str = "<?php echo date('Y-m-d',time());?>";
							 	strs=str.split("-");
							 								$(this).datepicker({
							 								minDate: new Date(strs[0], strs[1]-1, strs[2]),
							 							});  
								});
	//$("#date_from").val('<?php echo isset($date_from)?$date_from:""; ?>');
	$("#pay_way").val('<?php echo isset($pay_way)?$pay_way:""; ?>');
	if($("#pay_way").val()==0){
		$("#pay_way").removeAttr("disabled");
	}
	$("#pay_status").val('<?php echo isset($pay_status)?$pay_status:"10"; ?>');
	//初始化checkbox的状态
	$("input[type='checkbox']").each(function(){
		if(this.checked){
			this.checked=false;
		}
	});
	var ids="-";
	//点击全选和全不选
	$("#selectall").click(function(){
		if(this.checked){ 
			$("input[name='select']").each(function(){
				this.checked=true;
						
				//如果该复选框已经被选择，则获取其采购单的ID
				if(this.checked){
					var id=$(this).val();
					if(id=='on')
						return ;
					if(ids.indexOf(id)==-1){
							ids=ids+id+"-";
					}
				}
			});
		}else{ 
				ids="-";
				$("input[name='select']").each(function(){
					this.checked=false;
				}); 
		}
	});
		//点击单个单选按钮将其id拼入或者删除
		$("input[name='select']").click(function(){
			var id=$(this).val();
			if(this.checked){
				if(ids.indexOf(id)==-1){
					ids=ids+id+"-";
				}
				
			}else{
				var index=ids.indexOf(id);
				if(index!=-1){
					var idremove=ids.substr(index,id.length);
					var reg="-"+idremove+"-";
					ids=ids.replace(new RegExp(reg),"-");
				}
			}
		});
		//点击打印按钮，调用后台php代码
		$('#tijiao').click(function(){

			if(ids=='-'){
				alert("请选择");
				return;
			}else{

				var strs= new Array();
				strs=ids.split("-");
				var arr = new Array();
				for(var i=0;i<(strs.length-1);i++)
				{
						if(i==0)
						{
							arr[i] ={
											'money' :$("#p_id").children('td').eq(5).html(),
											'id'    :$("#p_id").children('td').eq(0).html(),
											'purchaseid':$("#p_id").children('td').eq(1).find("input").val(),
											'pay_way':$("#p_id").children('td').eq(3).find("select").val(),
											'transportation_expense':$("#p_id").children('td').eq(2).find("input").val(),
											'remark':$("#p_id").children('td').eq(6).find("input").val()
										}
							var mark = judge_supplier(arr[i]);
							if(!mark)
							{
								return ;
							}
						}else{
							arr[i] = {
							'tax_rate':$("#re_"+strs[i]).children('td').eq(7).find("input").val(),
							'arrive_date':$("#re_"+strs[i]).children('td').eq(8).find("input").val(),
							'tax_way':$("#re_"+strs[i]).children('td').eq(6).find("select").val(),
							'quantity':$("#re_"+strs[i]).children('td').eq(4).find("input").val(),
							'id':$("#re_"+strs[i]).children('td').eq(1).html(),
							'single_price':$("#re_"+strs[i]).children('td').eq(3).find("input").val(),
						}
							var flag = valicate_data(arr[i]);
							if(!flag)
							{
								return ;
							}
					}
				}
				
				var jdata=$.toJSON(arr);
				$.ajax({
					type:'POST',
					dataType:"json",
					url:"<?php echo URL::site() ?>purchase/update_purchase",
					async:false,
					data:{json:jdata},
					success:function(result){		
					if(result==0)
						{alert("状态不适合修改");return ;}			
					alert("修改成功");
				},		
				});
			}
		}); 				 
});
function atotle_price(obj)
{	
	var number=Number($(obj).parent().next().find("input").val());//alert(number);return ;
	var noneprices=obj.value;
	if(noneprices<0)
	{
		alert("单价小于0");return ;
	}
	var flag  = isInteger(noneprices);
	if(!flag)
	{
		alert("单价不是数字");return ;
	}
	var totles=Number(number*noneprices);
	if($(obj).parent().next().next().next().find('select').val()==1)
	{
		totles = Number(totles)*(1+Number($(obj).parent().parent().children('td').eq(7).find('input').val())/100).toFixed(2);
	}
	if(number=="" ){
		//document.getElementById("totle_ids").value=0;
	}else{
			var str  = $("#p_id").children('td').eq(5).html();
		 	var strs = $(obj).parent().next().next().html();
		 	var total =(Number(str.replace(/,/g,""))-Number(strs.replace(/,/g,""))+Number(totles)).toFixed(2);
			$(obj).parent().next().next().html(totles.toFixed(2));
			$("#p_id").children('td').eq(5).html(total);
	}
}
function atotle_s_price(obj)
{
	var number=obj.value;
	var noneprices=Number($(obj).parent().prev().find("input").val());
	var flag  = isInteger(number);
	if(!flag)
	{
		alert("数量不是数字");return ;
	}
	var totles=Number(number*noneprices);
	if($(obj).parent().next().next().find('select').val()==1)
	{
		totles = Number(totles)*(1+Number($(obj).parent().parent().children('td').eq(7).find('input').val())/100).toFixed(2);
	}
	if(number=="" ){
		//document.getElementById("totle_ids").value=0;
		}else{
			var str  = $("#p_id").children('td').eq(5).html();
		 	var strs = $(obj).parent().next().html();
		 	var total =(Number(str.replace(/,/g,""))-Number(strs.replace(/,/g,""))+Number(totles)).toFixed(2);
			//var total =(Number($("#p_id").children('td').eq(5).html())-Number($(obj).parent().next().html())+totles).toFixed(2);
			$(obj).parent().next().html(totles.toFixed(2));			
			$("#p_id").children('td').eq(5).html(total);
		}
}
function isInteger(val)
{
	if(!isNaN(val)){
   return true ;
	}else{
   return false;
	}
}
function judge_supplier(arr)
{
	var flag='';
	$.each(arr,function(key,value){
		/*if(key=='purchaseid'&&value=='')
		{
			flag = "单据号码为空";
		}
		else*/ if(key=='pay_way'&&value==0)
		{
			flag ="未选择付款方式";
		}	
		else if(key=='transportation_expense'&&(!judge(value)||value<0))
		{
			if(!judge(value))
				flag ="运费不是数字";
			if(value<0)
				flag ="运费小于0";
		}
		if(flag)
		{
			alert(flag);return false;
		}
	});
		if(flag) return false ;
		return true;
}
function valicate_data(arr)
{
	var flag='';		
	$.each(arr,function(key,value){

		if(key=='tax_rate'&&value!='0')
		{
			if(!isInteger(value))
			{
				alert("税率不是数字");
				flag = 1;
			}
			if(Number(value)>100||Number(value)<0)
			{
				alert("税率超出范围(0～100)");
				flag=1;
			}			
		}
		else if(key=='arrive_date'&&value=='')
		{
				alert("交货日期为空");
				flag = 1;
		}
		else if(key=='tax_way'&&value==0)
		{
			//flag ="";
		}	
		else if(key=='quantity'&&(value==''||value==0))
		{
			alert("未填数量"); flag=1;
		}
		else if(key=='single_price'&&(!judge(value)||value<=0))
		{
			if(!judge(value))
			{
				alert("单价不是数字");
				flag=1;
			}
			else
			{
				alert("单价小于等于0");
				flag=1;
			}
		}

		if(flag)
			return false;
	});
		if(flag) return false ;
	return true;
}
function judge(factpay){

	if(!isNaN(factpay)){

		return true;;
	}else{
		return false;
	}
}
function delete_purchase(p_detail_id)
{
	if(!window.confirm("确定取消吗？"))
	{
		return ;
	}
	$.post(
				"<?php echo URL::site(); ?>purchase/deletepurchase",
				{p_detail_id:p_detail_id},
				function(re){
					//alert(re);return ;
						if(re=='"cancel success"')
						{
							$("re_"+p_detail_id).text("取消");
							alert("取消成功");
						}
						else if(re=='"flag"')
						{ 					
							alert("完结成功");
							$("re_"+p_detail_id).text("手动完结");
						}else{
							alert("状态不适合完结或取消");
						}
		});
}
</script>
	<table class="table table-bordered table_syb">
	 <tr class="headings">                             
                                    <th >
                                        采购单号
                                    </th>
                                    <th style="display: none">
                                        单据号码
                                    </th>
				    												<th>
                                        运费
                                    </th>
                                    <th colspan="2">
                                        付款方式
                                    </th>
																		<th colspan="2">
																			  状态
																		</th >
																		<th colspan="2">
                                       	采购总额
                                    </th>
																		<th colspan="2">
                                       	备注
                                    </th>																	
                                </tr>
<?php if(isset($purchaseorder_info)&&!empty($purchaseorder_info)) {?>
	 <tr class="headings" id="p_id">                             
                                    <td >
                                     <?php echo  $purchaseorder_info['id'] ?>   
                                    </td>
                                    <td style="display: none">
                                     <input class="input-mini" type="text" value="<?php if(isset($purchaseorder_info['purchaseid'])) echo $purchaseorder_info['purchaseid'];?>" style="width: 100px">
                                    </td>
				    												<td>
                                        <input class="input-mini" type="text" value="<?php if(isset($purchaseorder_info['transportation_expense'])) echo number_format($purchaseorder_info['transportation_expense'],2);?>">
                                    </td>
                                    <td colspan="2">
																			<select class="input-xlarge"  name="paytype" id="pay_way" style="width: 100px">
                               					<option value="0">选择付款方式</option>
                                    <?php foreach($payways as $pay_way_id=>$payway){?>
                                        <option value="<?php echo $pay_way_id;?>" <?php if(isset($purchaseorder_info['pay_way'])&&$pay_way_id==$purchaseorder_info['pay_way']){echo "selected='selected'";}?>>
                                            <?php echo $payway;?>
                                        </option>
                                    <?php }?>
                                  		</select>
                                    </td>
																		<td colspan="2">
																		 <?php echo $purchaseorder_info['status'] ?> 	  
																		</td >
																		<td colspan="2" id="all_money">
                                     <?php echo  number_format($purchaseorder_info['money'],3) ?>
                                    </td>
																		<td colspan="2">
                                     <input class="input-mini" type="text" value="<?php if(isset($purchaseorder_info['remark'])) echo $purchaseorder_info['remark'];?>" style="width:120px">   	
                                    </td>
                                </tr>
<?php }?>
	 <tr class="headings">
                                    <th >
                                       选择
                                    </th>                             
                                    <th>
                                        明细单号
                                    </th>
                                    <th>
                                        SKU
                                    </th>
				    												<th >
                                        产品单价
                                    </th>
																		<th >
                                       	采购数量
                                    </th>
																		<th >
                                       	总额
                                    </th>
				    												<th >
                                        计税
                                    </th>
                                    <th >
                                        税率
                                    </th>
																		<th >
                                        交货日期
                                    </th>
																		<th>
                                        状态
                                    </th>	
                                </tr>
<?php if(isset($purchaseorder_detail)&&!empty($purchaseorder_detail)) {?>
						<?php foreach ($purchaseorder_detail as $p_in){?>
																<tr id="re_<?php echo $p_in['id']?>">
                                    <td>
                                        <input type="checkbox" name="select" value="<?php echo $p_in['id']?>">
                                    </td>
                                    <td >
                                        <?php echo $p_in['id']?>
                                    </td>
                                    <td >
                                        <?php echo $p_in['sku']." : ".$p_in['sku_name'];?>
                                    </td>
                                    <td >
                                       <input class="input-mini" type="text" value="<?php if(isset($p_in['single_price'])) echo $p_in['single_price']?>" onBlur="atotle_price(this)">
                                    </td>
				    												<td >
                                       <input class="input-mini" type="text" value="<?php if(isset($p_in['quantity'])) echo $p_in['quantity']?>" onBlur="atotle_s_price(this)" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')">
                                    </td>
																		<td >
                                       	<?php echo number_format($p_in['money'],2)?>
                                    </td>
				    												<td >
																			<select class="input-xlarge field"  name="tax_way" id="tax_way" style="width: 75px">
																				<?php foreach ($tax_ways as $tax_way){?>
																				<option value="<?php echo $tax_way['id']?>" <?php if(trim($tax_way['id']) == $p_in['tax_way']){
																				echo "selected='selected'";}?>>
																				<?php echo $tax_way['tax_way']?>
																				</option>	
																				<?php }?>
																			</select>                                        
                                    </td>
                                    <td >
                                        <input class="input-mini tax_rate" type="text" value="<?php if(isset($p_in['tax_rate'])) echo $p_in['tax_rate']*100 ?>">%
                                    </td>
																		<td >
                                        <input class="input-mini datepicker" type="text" value="<?php if(isset($p_in['arrive_date'])) echo $p_in['arrive_date']?>">
                                    </td>
				    												<td >
                                        <?php echo $p_in['status']?>
                                    </td>	 						
																										
																</tr>
<?php }}?>
	</table>
&nbsp;<input type="checkbox"  id="selectall">&nbsp;&nbsp;<button id="tijiao" class="btn btn-success">一键修改</button></div><hr/>
<button class="btn btn-success" type="button"  onclick="add_sku()">增加SKU</button>
<button class="btn btn-warning" type="button"  onclick="dec_sku()">减少SKU</button>
<span style="display: none;"  id="tr_num_add" >0</span>
<span style="display: none;"  id="tr_num" >0</span>
<input id="supplier_id" type="text" style="display: none" value="<?php echo isset($purchaseorder_info['supplier_id'])?$purchaseorder_info['supplier_id']:0;?>">
<input id="pu_id" type="text" style="display: none" value="<?php echo isset($purchaseorder_info['id'])?$purchaseorder_info['id']:0;?>">

<table class="table">
    <thead>
        <tr style="  background-color:#4EA392; color:#fff;">
            <th>SKU</th>
            <th>中文名称</th>
            <th>单位</th>
            <th>储位</th>
            <th>计税方式</th>
            <th>单价</th>
            <th>数量</th>
            <th>税率</th>
            <th>金额</th>
            <th>交货日期</th>
            <th>系统成本价</th>
            <th>状态</th>
        </tr>

    </thead>

    <tbody class="add_sku_tbl" style=""></tbody>
</table>
<button onclick="to_add()" class="btn btn-success">提交</button>


<script type="text/javascript">
    function check_pu(pu_id)
    {
        $.ajax(
            {
                type: 'post',
                url: '<?php echo url::base(true)?>purchase/check_have_plan',
                dataType: 'json',
                data: {"pu_id": pu_id},
                async: false,
                success: function (re_data) {
                    if(re_data.ok==0)
                    {
                        alert('该采购单已计划');
                        flag = false;
                    }
                }
            }
        );
        return flag;
    }
    function add_sku()
    {
        //if(!check_pu($("#pu_id").val()))return false;
        var num = parseInt($("#tr_num_add").text());
        $.ajax(
            {
                type: 'post',
                url: '<?php echo url::base(true)?>purchase/add_sku',
                dataType: 'json',
                data: {"num": num},
                async: false,
                success: function (re_data) {
                    if(re_data)
                    {
                        show_add_row(re_data);
                    }
                }
            }
        );
    }

    //添加一行
    function show_add_row(data)
    {
        if(data.num)
        {
            $("#tr_num_add").text(data.num);
            var num = parseInt($("#tr_num").text())+1;
            $("#tr_num").text(num);
        }
        if(data.view)
        {
            $(".add_sku_tbl").append(data.view);
        }
    }


    //减少一行sku
    function dec_sku()
    {
        var num = parseInt($("#tr_num_add").text());
        if(num>1)
        {
            $(".add_sku_tbl").children("tr").last().remove();
            num--;
            $("#tr_num_add").text(num);
        }else{
            $("#tr_num_add").text(0);
            $(".add_sku_tbl").empty();
        }

    }

    function check_double(pu_id,sku)
    {
        var flag = true;
        $.ajax(
            {
                type: 'post',
                url: '<?php echo url::base(true)?>purchase/check_double_sku',
                dataType: 'json',
                data: {"pu_id": pu_id,"sku":sku},
                async: false,
                success: function (re) {
                    if(re.ok)
                    {
                        return true;
                    }
                    else
                    {
                        alert('该采购单已包含该sku');
                        flag = false;
                    }
                },
                error: function () {
                }
            }
        );
        return flag;
    }

    /**
     * 获取SKU数据
     */
    function check_sku(obj)
    {
        var supplier_id = $("#supplier_id").val();
        var sku = $(obj).val();
        if ( supplier_id != ''
            && sku != ''
            && !$(obj).attr('readonly') )
        {
            if(!check_double($("#pu_id").val(),sku)) return false;
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/getskuinfo',
                    dataType: 'json',
                    data: {"supplier_id": supplier_id,"sku":sku},
                    async: false,
                    success: function (re_data) {
                        if(re_data && re_data.sku)
                        {
                            $(obj).val(re_data.sku);
                            $(obj).attr("readonly", "readonly");
                            get_supplier_sku_info(supplier_id,re_data.sku,obj);
                        }
                        else
                        {
//                        $(obj).focus();
                            alert('该供应商没有找到这个SKU信息');
                            return false;
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }

    /**
     * 选中sku之后再补全sku信息
     */
    function get_supplier_sku_info(supplier_id,sku,obj)
    {
        var id  =  $(obj).parent().parent().attr('id');
        if(supplier_id
            && sku)
        {
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/getskuinfo',
                    dataType: 'json',
                    data: {"supplier_id": supplier_id,"sku":sku},
                    async: false,
                    success: function (re_data) {
                        if(re_data)
                        {
                            show_supplier_sku_info(id,re_data);
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }

    /**
     * 显示供应商的SKU信息，sku信息
     * 指定的行号
     */
    function show_supplier_sku_info(id,supplier_sku_info)
    {
        if(supplier_sku_info)
        {
            if(supplier_sku_info.sku)
            {
                $("#"+id).children().eq(0).find("input").val(supplier_sku_info.sku);
            }
            if(supplier_sku_info.sku_name)
            {
                $("#"+id).children().eq(1).text(supplier_sku_info.sku_name);
            }
            if(supplier_sku_info.nuit)
            {
                $("#"+id).children().eq(2).text(supplier_sku_info.nuit);
            }
            if(supplier_sku_info.place)
            {
                $("#"+id).children().eq(3).text(supplier_sku_info.place);
            }
            if(supplier_sku_info.price)
            {
                $("#"+id).children().eq(5).find("input").val(supplier_sku_info.price);
            }
            if(supplier_sku_info.delivery)
            {
                $("#"+id).children().eq(9).find("input").val(supplier_sku_info.delivery);
            }
            if(supplier_sku_info.sku_price)
            {
                $("#"+id).children().eq(10).text(supplier_sku_info.sku_price);
            }
            if(supplier_sku_info.status)
            {
                $("#"+id).children().eq(11).text(supplier_sku_info.status);
            }
        }
    }

    /**
     * 自动提示供应商的sku信息
     */
    function do_autocomplete(obj)
    {
        var supplier_id = $("#supplier_id").val();
        if ( supplier_id != ''
            && !$(obj).attr('readonly')
            && !$(obj).data("autocomplete") )
        {
            $(obj).autocomplete({
                autoFocus: true,
                minLength: 0,
                autoFill: true,
                source: '<?php echo URL::base(true)?>purchase/get_supplier_sku?supplier_id='+supplier_id,
                select: function (event, ui) {
                    /**
                     * 从建议列表中选中之后触发的事件
                     */
                    $(obj).val(ui.item.sku);
                    $(obj).attr("readonly", "readonly");
                    get_supplier_sku_info(supplier_id,ui.item.sku,this);
                    return false;
                }
            });
        }
    }


    /**
     * 获取计算金额的信息
     */
    function get_money_info(obj)
    {
        var id  =  $(obj).parent('td').parent('tr').attr('id');

        if(!$("#"+id).children('td').eq(0).find('input').attr('readonly'))
        {
            return false;
        }
        var money_info = {
            "quantity":$("#"+id).children('td').eq(6).find('input').val(),
            "single_price":$("#"+id).children('td').eq(5).find('input').val(),
            "tax_rate":$("#"+id).children('td').eq(7).find('input').val(),
            "tax_way":$("#"+id).children('td').eq(4).find("select").val()
        }

        return money_info;
    }

    function show_money(obj,money)
    {
        if(money){
            var id  =  $(obj).parent('td').parent('tr').attr('id');
            $("#"+id).children('td').eq(5).find('input').val(money.single_price);
            $("#"+id).children('td').eq(6).find('input').val(money.quantity);
            $("#"+id).children('td').eq(7).find('input').val(money.tax_rate);
            $("#"+id).children('td').eq(8).find('input').val(money.money);
        }
    }

    function check_single_price(obj)
    {
        var id  =  $(obj).parent('td').parent('tr').attr('id');

        if(!$("#"+id).children('td').eq(0).find('input').attr('readonly'))
        {
            return false;
        }
        var sku=$("#"+id).children('td').eq(0).find("input").val();
        var single_price=$("#"+id).children('td').eq(5).find('input').val();
        if(single_price){
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/check_single_price',
                    dataType: 'json',
                    data: {"single_price":single_price,'sku':sku},
                    async: false,
                    success: function (re_data) {
                        if(re_data.code==2)
                        {
                            alert('注意：单价高于基础资料系统单价');
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }

    function check_sku_status(obj)
    {
        var id  =  $(obj).parent('td').parent('tr').attr('id');

        if(!$("#"+id).children('td').eq(0).find('input').attr('readonly'))
        {
            return false;
        }
        var sku=$("#"+id).children('td').eq(0).find("input").val();
        $.ajax(
            {
                type: 'post',
                url: '<?php echo url::base(true)?>purchase/check_sku_status',
                dataType: 'json',
                data: {'sku':sku},
                async: false,
                success: function (re_data) {
                    if(re_data.code==2)
                    {
                        alert(re_data.mes);
                    }
                },
                error: function () {
                    alert('系统错误');
                }
            }
        );
    }

    /**
     * 计算价格与基础资料价格进行比较，如果大于，则不允许下单
     */
    function count_money_and_price(obj)
    {
        check_single_price(obj);
        var money_info = get_money_info(obj);
        if(money_info){
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/count_money',
                    dataType: 'json',
                    data: {"money_info":money_info},
                    async: false,
                    success: function (re_data) {
                        if(re_data)
                        {
                            show_money(obj,re_data);
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }
    //输入数量后提示
    function count_money_in_count(obj)
    {
        var td_single_price = $(obj).parent().prev().find("input");
        check_sku_status(td_single_price);
        check_single_price(td_single_price);
        var money_info = get_money_info(obj);
        if(money_info){
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/count_money',
                    dataType: 'json',
                    data: {"money_info":money_info},
                    async: false,
                    success: function (re_data) {
                        if(re_data)
                        {
                            show_money(obj,re_data);
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }

    /**
     * 重新计算金额
     */
    function count_money(obj)
    {
        check_single_price();
        var money_info = get_money_info(obj);
        if(money_info){
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/count_money',
                    dataType: 'json',
                    data: {"money_info":money_info},
                    async: false,
                    success: function (re_data) {
                        if(re_data)
                        {
                            show_money(obj,re_data);
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }

    function get_purchase_sku_info_row(id)
    {
        if($("#"+id).children('td').find('input').attr('readonly'))
        {
            var sku_info= {
                "sku":$("#"+id).children('td').eq(0).find("input").val(),
                "sku_name":$("#"+id).children('td').eq(1).text(),
                "storage_position":$("#"+id).children('td').eq(3).text(),
                "sku_standard":"",
                "quantity":$("#"+id).children('td').eq(6).find('input').val(),
                "single_price":$("#"+id).children('td').eq(5).find('input').val(),
                "tax_rate":$("#"+id).children('td').eq(7).find('input').val(),
                "remark":"",
                "arrive_date":$("#"+id).children('td').eq(9).find('input').val(),
                "tax_way":$("#"+id).children('td').eq(4).find("select").val(),
                "sku_unit":$("#"+id).children('td').eq(2).text(),
                "prime_cost":$("#"+id).children('td').eq(10).text(),
                "supplier":$('#supplier_id').val()
            }

            return sku_info;
        }
        else
        {
            return false;
        }
    }

    function to_add()
    {
        if(parseInt($("#tr_num_add").text())==0)
        {
            return false;
        }
        var sku_info_adds = [];
        $(".add_sku_tbl").children('tr').each(function(){
            var sku_info = get_purchase_sku_info_row($(this).attr('id'));
            if(sku_info)
            {
                sku_info_adds.push(sku_info);
            }
        });

        if(sku_info_adds)
        {
            $.ajax(
                {
                    type: 'post',
                    url: '<?php echo url::base(true)?>purchase/to_add',
                    dataType: 'json',
                    data: {"pu_id": parseInt($("#pu_id").val()),"skus":sku_info_adds},
                    async: false,
                    success: function (re_data) {
                        if(re_data.append)
                        {
                            $(".table_syb").append(re_data.append);
                            $(".add_sku_tbl").empty();
                            $("#all_money").text(re_data.all_money);
                            //window.location.reload();
                        }
                    },
                    error: function () {
                    }
                }
            );
        }
    }

</script>

